<!--
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 * No deletion without permission, or be held responsible to law.
 * @author PR
-->
<template>
  <BasicDrawer
    v-bind="$attrs"
    :showFooter="true"
    :okAuth="'asd:tz:asdTmTz:edit'"
    :show-ok-btn="false"
    @register="registerDrawer"
    @ok="handleSubmit"
    width="80%"
  >
    <template #title>
      <Icon :icon="getTitle.icon" class="pr-1 m-1" />
      <span> {{ getTitle.value }} </span>
    </template>
    <BasicForm @register="registerForm">
      <template #u8SumList>
        <ListSelect
          v-model:value="itemCodes"
          :labelValue="itemNames"
          :selectType="selectType"
          :params="queryParams"
          :checkbox="false"
          @select="handSelect"
        />
      </template>
      <template #invSelect>
        <ListSelect
          v-model:value="invCodes"
          :labelValue="invNames"
          selectType="invSelect"
          :checkbox="false"
          @select="handleInvSelect"
        />
      </template>
    </BasicForm>

    <template #appendFooter>
      <a-button type="primary" :loading="loading" v-if="record.allowDel" @click="handleSubmit()">
        <Icon icon="ant-design:check-outlined" /> {{ t('确认') }}
      </a-button>
    </template>
  </BasicDrawer>
</template>
<script lang="ts">
  export default defineComponent({
    name: 'ViewsAsdTzAsdTmTzForm',
  });
</script>
<script lang="ts" setup>
  import { defineComponent, ref, computed } from 'vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { router } from '/@/router';
  import { Icon } from '/@/components/Icon';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import { AsdTmTz, asdTmTzSave, asdTmTzForm } from '/@/api/asd/tz/asdTmTz';
  import { ListSelect } from '/@/components/ListSelect';
  import { posTreeData } from '/@/api/bas/pos';

  const emit = defineEmits(['success', 'register']);

  const { t } = useI18n('asd.tz.asdTmTz');
  const { showMessage } = useMessage();
  const record = ref<AsdTmTz>({} as AsdTmTz);
  let loading = ref(false);
  const getTitle = computed(() => ({
    icon: router.currentRoute.value.meta.icon || 'ant-design:book-outlined',
    value: record.value.isNewRecord ? t('新增货位调整') : t('编辑货位调整'),
  }));

  const itemCodes = ref('');
  const itemNames = ref('');
  const selectType = ref('u8PosSelect');
  const queryParams = ref({
    cinvcode: '',
  });

  // 物料选择相关变量
  const invCodes = ref('');
  const invNames = ref('');

  const bshelf = ref<string>('0');
  const inputFormSchemas: FormSchema[] = [
    {
      label: t('物料代码'),
      field: 'basInv.cinvaddcode',
      component: 'Input',
      required: true,
      dynamicDisabled: true,
    },
    {
      label: t('物料编码'),
      field: 'basInv.cinvcode',
      component: 'Input',
      required: true,
      dynamicDisabled: true,
    },
    {
      label: t('物料名称'),
      field: 'basInv.cinvname',
      component: 'Input',
      colProps: { lg: 24, md: 24 },
      slot: 'invSelect',
      required: true,
    },

    {
      label: t('调整前货位'),
      field: 'cposname',
      component: 'Input',
      colProps: { lg: 24, md: 24 },
      componentProps: {
        placeholder: '',
        onclick: () => {
          handleSelect();
        },
      },
      required: true,
    },
    {
      label: t('调整前货位'),
      field: 'pos',
      component: 'Input',
      colProps: { lg: 24, md: 24 },
      slot: 'u8SumList',
      show: false,
    },
    {
      label: t('调整前货位'),
      field: 'cbcpos',
      fieldLabel: 'cposname',
      component: 'Input',
      colProps: { lg: 24, md: 24 },
      required: true,
      show: false,
    },
    {
      label: t('调整后货位'),
      field: 'cacpos',
      component: 'TreeSelect',
      componentProps: ({ formModel }) => {
        return {
          params: { isAll: true, cwhcode: formModel.cwhcode, bshelf: bshelf.value },
          api: posTreeData,
          canSelectParent: false,
          allowClear: true,
        };
      },
      required: true,
    },
    {
      label: t('数量'),
      field: 'iqty',
      component: 'Input',
      componentProps: {
        maxlength: 16,
      },
      rules: [
        { required: true },
        { pattern: /^(?:-?\d+|-?\d{1,3}(?:,\d{3})+)?(?:\.\d+)?$/, message: t('请输入一个数值') },
      ],
    },
    {
      label: t('仓库'),
      field: 'cwhcode',
      component: 'Select',
      componentProps: {
        dictType: 'ASD_WH',
      },
      required: true,
      dynamicDisabled: true,
    },
    {
      label: t('批次'),
      field: 'cbatch',
      component: 'Input',
      componentProps: {
        maxlength: 64,
      },
      required: true,
      dynamicDisabled: true,
    },
    {
      label: t('备注'),
      field: 'remarks',
      component: 'InputTextArea',
      componentProps: {
        maxlength: 500,
      },
      colProps: { lg: 24, md: 24 },
    },
  ];

  const [registerForm, { resetFields, setFieldsValue, validate, getFieldsValue }] = useForm({
    labelWidth: 120,
    schemas: inputFormSchemas,
    baseColProps: { lg: 24, md: 24 },
  });

  function handleSelect() {
    const data = getFieldsValue();
    if (data.basInv.cinvcode) {
      queryParams.value.cinvcode = data.basInv.cinvcode;
      document.getElementById('form_item_pos')?.click();
    } else {
      showMessage('请先选择物料!');
    }
  }

  /**
   * 选择
   * @param selectData
   */
  function handSelect(selectData: any[]) {
    if (selectType.value === 'u8PosSelect') {
      selectData.forEach((item) => {
        console.log(item);
        var data = getFieldsValue();
        data.cbcpos = item.cposcode;
        data.cposname = item.cposname;
        data.iqty = item.iqty;
        data.cbatch = item.cbatch;
        data.cwhcode = item.cwhcode;
        setFieldsValue(data);
      });
    }
  }

  /**
   * 物料选择处理
   * @param selectData
   */
  function handleInvSelect(selectData: any[]) {
    if (selectData && selectData.length > 0) {
      const selectedItem = selectData[0];
      const data = getFieldsValue();

      // 设置物料编码、物料名称和物料代码
      data['basInv.cinvcode'] = selectedItem.cinvcode || '';
      data['basInv.cinvname'] = selectedItem.cinvname || '';
      data['basInv.cinvaddcode'] = selectedItem.cinvaddcode || '';

      // 更新显示值
      invCodes.value = selectedItem.cinvcode || '';
      invNames.value = selectedItem.cinvname || '';

      setFieldsValue(data);
    }
  }

  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    loading.value = true;
    setDrawerProps({ loading: true });
    await resetFields();
    bshelf.value = data.bshelf;
    const res = await asdTmTzForm(data);
    record.value = (res.asdTmTz || {}) as AsdTmTz;
    record.value.__t = new Date().getTime();

    // 先设置表单值
    await setFieldsValue(record.value);

    // 然后设置物料显示值
    setTimeout(() => {
      console.log('原始数据:', record.value);
      const formData = getFieldsValue();
      console.log('表单数据:', formData);

      // 设置物料编码、物料名称显示值
      const recordData = record.value as any;
      if (recordData.basInv) {
        invCodes.value = recordData.basInv.cinvcode || '';
        invNames.value = recordData.basInv.cinvname || '';
      } else if (formData.basInv) {
        invCodes.value = formData.basInv.cinvcode || '';
        invNames.value = formData.basInv.cinvname || '';
      } else {
        // 如果是扁平结构，尝试直接访问
        invCodes.value = recordData['basInv.cinvcode'] || formData['basInv.cinvcode'] || '';
        invNames.value = recordData['basInv.cinvname'] || formData['basInv.cinvname'] || '';
      }

      console.log('设置显示值:', { invCodes: invCodes.value, invNames: invNames.value });
    }, 100);

    loading.value = false;
    setDrawerProps({ loading: false });
  });

  async function handleSubmit() {
    try {
      const data = await validate();
      setDrawerProps({ confirmLoading: true });
      const params: any = {
        isNewRecord: record.value.isNewRecord,
        djno: record.value.djno,
      };
      // console.log('submit', params, data, record);
      const res = await asdTmTzSave(params, data);
      showMessage(res.message);
      setTimeout(closeDrawer);
      emit('success', data);
    } catch (error: any) {
      if (error && error.errorFields) {
        showMessage(t('您填写的信息有误，请根据提示修正。'));
      }
      console.log('error', error);
    } finally {
      setDrawerProps({ confirmLoading: false });
    }
  }
</script>
